import { getArticleDetail, getArticleList } from '@/services';
import { IArticleItem, IArticleItemDetail } from '@/utils/type';
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

// 定义模块内部状态的类型
export interface ArticleModelState {
  articles: IArticleItem[];
  // artilceDetail: Partial<IArticleItemDetail>
  artilceDetail: IArticleItemDetail

}

// 定义模块的类型
export interface ArticleModelType {
  namespace: 'article';
  state: ArticleModelState;
  effects: {
    getArticleList: Effect;
    getArticleDetail: Effect;
  };
  reducers: {
    save: Reducer<ArticleModelState>;
  };
}

const ArticleModel: ArticleModelType = {
  // 模块命名空间
  namespace: 'article',

  // 模块内部状态
  state: {
    articles: [],
    artilceDetail: {} as IArticleItemDetail,
  },

  // 副作用
  effects: {
    *getArticleList({ payload }, { call, put }) {
      const result = yield call(getArticleList);
      if (result.statusCode === 200) {
        yield put({
          type: 'save',
          payload: {
            articles: result.data[0]
          }
        })
      }
    },
    * getArticleDetail({payload}, { call, put }) {
      const result = yield call(getArticleDetail, payload);
      console.log('result', result);
      if (result.statusCode === 200){
        yield put({
          type: 'save',
          payload: {
            artilceDetail: result.data
          }
        })
      }
    }
  },

  // 同步修改
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    }
  }
};

export default ArticleModel;